import { ref, onMounted } from "vue";
import ToolAction from "@/tool/http/tool-action.js";

export default function use({ queryParam = {} }, code, rowsWatch = () => {}) {
  let api = ToolAction.init(code);

  const rows = ref([]);

  onMounted(() => {
    api.list(queryParam).then((res) => {
      rows.value = res;
    });
  });

  const remove = (id) => {
    api.remove(id).then(() => {
      rows.value = rows.value.filter((row) => row.id !== id);
      rowsWatch(rows.value);
    });
  };

  const sync = async (row) => {
    row = await api.sync(row);
    if (rows.value.find((item) => item.id === row.id)) {
      return;
    }
    rows.value.push(row);
    rowsWatch(rows.value);
  };

  return {
    rows,
    remove,
    sync,
  };
}
